package com.yupi.project.controller;

import com.yupi.project.service.MailService;
import com.yupi.yuapicommon.model.common.*;
import com.yupi.yuapicommon.model.dto.email.EmailAuthCodeRequest;
import com.yupi.yuapicommon.model.dto.user.UserLoginRequest;
import com.yupi.yuapicommon.utils.ImageCaptchaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/mail")
@Api("邮箱服务相关")
@Slf4j
public class MailController {

    @Resource
    private MailService mailService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String CACHE_KEY = "imageCaptcha:";

    /**
     * 通过邮箱获取验证码
     *
     * @param emailAuthCodeRequest
     * @param request
     * @return
     */
    @PostMapping("/send")
    @ApiOperation("通过邮箱获取验证码")
    public BaseResponse<Boolean> sendMail(@RequestBody EmailAuthCodeRequest emailAuthCodeRequest, HttpServletRequest request) {
        if (emailAuthCodeRequest == null || StringUtils.isBlank(emailAuthCodeRequest.getUserEmail())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean sendMimeMail = mailService.sendMimeMail(emailAuthCodeRequest.getUserEmail());
        if(!sendMimeMail){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "邮件发送失败");
        }
        return ResultUtils.success(sendMimeMail);
    }

    /**
     * 生成图片验证码
     * @param request
     * @return
     */
    @GetMapping("/genImageCaptcha")
    @ApiOperation("生成图片验证码")
    public BaseResponse<String> genImageCaptcha(HttpServletRequest request) {
        ImageCaptchaResult result = null;
        try {
            result = ImageCaptchaUtil.createBase64ForWeb(new ImageCaptchaParams());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("生成图片验证码：{}\n Base64字符串是：{}", result.getWords(), result.getReturnContent());
        stringRedisTemplate.opsForValue().set(CACHE_KEY + request.getSession().getId(), result.getWords(), 5, TimeUnit.MINUTES);
        return ResultUtils.success(result.getReturnContent());
    }

    /**
     * 验证图片验证码
     * @param imageCaptcha
     * @param request
     * @return
     */
    @PostMapping("/verifyImageCaptcha")
    @ApiOperation("验证图片验证码")
    public BaseResponse<Boolean> verifyImageCaptcha(@RequestParam("imageCaptcha") String imageCaptcha, HttpServletRequest request) {
        boolean result = false;
        String key = CACHE_KEY + request.getSession().getId();
        String cache = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(cache) && cache.equals(imageCaptcha)) {
            result = true;
            //stringRedisTemplate.opsForValue().set(key, "success", 5, TimeUnit.MINUTES);
        }
        return ResultUtils.success(result);
    }
}
